<template>
  <view class="search-page">
    <!-- 渐变背景区域 -->
    <view class="gradient-section">
      <!-- 状态栏占位 -->
      <view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
      <!-- 顶部返回按钮区域 -->
      <view class="header-section" :style="{ 'padding-right': customRightPadding + 'px' }">
        <view class="back-title-section">
          <view class="back-button" @click="goBack">
            <uni-icons type="left" size="24" color="#333" />
          </view>
        </view>
      </view>
      
      <view class="search-bar">
        <uni-icons type="search" size="22" color="#bfbfbf" />
        <input
          class="search-input"
          placeholder="搜索目的地/电站"
          v-model="searchValue"
          @input="onInput"
        />
        <!-- 清空按钮 -->
        <view 
          v-if="searchValue.trim()" 
          class="clear-btn" 
          @click="clearInput"
        >
          <uni-icons type="clear" size="18" color="#999" />
        </view>
        <button confirm-type="search" class="search-btn" @click="onSearch">搜索</button>
      </view>
    </view>
    
    <!-- 内容区域 -->
    <view class="content-section">
      <view v-if="!showResult" class="history-card">
        <view class="history-header">
          <text class="history-title">历史搜索</text>
          <uni-icons type="trash" size="22" color="#bfbfbf" class="history-clear" @click="clearHistory" />
        </view>
        <view class="history-list" v-if="historyList.length > 0">
          <view
            class="history-tag"
            v-for="(item, idx) in historyList"
            :key="idx"
            @click="selectHistory(item)"
          >
            {{ item }}
          </view>
        </view>
        <view class="history-empty" v-else>
          <text class="empty-text">暂无搜索历史</text>
        </view>
      </view>
      <view v-else>
        <scroll-view 
          scroll-y="true" 
          class="station-list"
          @scrolltolower="loadMore"
          :show-scrollbar="true"
          :enhanced="true"
          :bounces="false"
        >
          <view class="station-item" 
            v-for="(station, index) in stationList" 
            :key="index" 
            @click="goToStationDetail(station)"
            :class="{ 'station-item-with-shop': station.shopName }"
          >
            <view class="station-info">
              <view class="station-jam" v-if="station.shopName">
                <text class="station-jam-text">利行驿站</text>
              </view>
              <view class="station-header">
                <text class="station-name">{{ station.name || '未知站点' }}</text>
                <view class="station-distance">
                  <uni-icons type="paperplane-filled" />
                  <text class="distance-text">{{ station.distance || '距离未知' }}</text>
                </view>
              </view>
              <view class="station-details">
                <text class="station-facilities">{{ station.facilities || '暂无设施信息' }}</text>
              </view>
              <view class="station-pricing">
                <text class="price-label">¥</text>
                <text class="price-amount">{{ station.price || '0.00' }}</text>
                <text class="price-unit">元/度 起</text>
                <view class="station-status">
                  <view class="station-rating-rateIcon">
                    <text class="station-rating-rate">快</text>
                  </view>
                  <view class="station-rating-text-numBg">
                    <text class="station-rating-text-num">闲{{ station.fastRate || '0/0' }}</text>
                  </view>
                </view>
              </view>
              <view class="member-price-badge">
                <view class="member-price-label">会员价</view>
                <view class="member-price-value">0.85元/度</view>
              </view>
              <view class="station-rating">
                <view class="station-rating-icon">
                  <text class="station-rating-p">P</text>
                </view>
                <view class="station-rating-text-bg">
                  <text class="station-rating-text">{{ station.parkFee || '停车信息未知' }}</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 加载更多提示 -->
          <view class="loading-more" v-if="loading && stationList.length > 0">
            <text class="loading-text">正在加载更多...</text>
          </view>
          
          <!-- 没有更多数据提示 -->
          <view class="no-more" v-if="!loading && stationList.length > 0 && !hasMore">
            <text class="no-more-text">没有更多数据了</text>
          </view>
          
          <!-- 空状态 -->
          <view class="empty-state" v-if="!loading && stationList.length === 0 && showResult">
            <text class="empty-text">未找到相关充电站</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { getChargeStationList } from '@/api/charging/index.js'

export default {
  components: {
    uniPopup,
    uniIcons
  },
  data() {
    return {
      searchValue: '',
      historyList: [], // 改为空数组，从本地存储读取
      showResult: false,
      stationList: [],
      loading: false,
      page: 1,
      total: 0,
      hasMore: true,
      statusBarHeight: 0, // 新增状态栏高度
      customRightPadding: 0 // 新增自定义右侧padding
    }
  },
  onLoad() {
    // 页面加载时读取搜索历史
    this.loadSearchHistory();
    // 获取状态栏高度
    this.getStatusBarHeight();
    // 获取自定义右侧padding
    this.getCustomRightPadding();
  },
  methods: {
    // 加载搜索历史
    loadSearchHistory() {
      try {
        const history = uni.getStorageSync('searchHistory') || [];
        this.historyList = history;
      } catch (error) {
        console.error('读取搜索历史失败:', error);
        this.historyList = [];
      }
    },
    
    // 保存搜索历史
    saveSearchHistory(keyword) {
      if (!keyword || !keyword.trim()) {
        console.log('关键词为空，不保存历史');
        return;
      }
      
      console.log('准备保存搜索历史，关键词:', keyword);
      
      try {
        let history = uni.getStorageSync('searchHistory') || [];
        console.log('当前历史记录:', history);
        
        // 移除重复项
        history = history.filter(item => item !== keyword.trim());
        console.log('去重后历史记录:', history);
        
        // 添加到开头
        history.unshift(keyword.trim());
        console.log('添加新记录后:', history);
        
        // 只保留最近20条记录
        if (history.length > 20) {
          history = history.slice(0, 20);
          console.log('截取后历史记录:', history);
        }
        
        // 保存到本地存储
        uni.setStorageSync('searchHistory', history);
        console.log('已保存到本地存储');
        
        // 更新页面数据
        this.historyList = history;
        console.log('页面数据已更新，当前historyList:', this.historyList);
        
        console.log('搜索历史保存完成:', history);
      } catch (error) {
        console.error('保存搜索历史失败:', error);
      }
    },
    
    onSearch() {
      if (this.searchValue.trim()) {
        console.log('开始搜索，关键词:', this.searchValue);
        
        // 保存搜索历史
        this.saveSearchHistory(this.searchValue);
        
        // 重新加载历史记录以确保显示最新
        this.loadSearchHistory();
        
        this.showResult = true;
        this.page = 1; // 重置页码
        this.stationList = []; // 清空列表
        this.searchStations(); // 执行搜索
      } else {
        this.showResult = false;
      }
    },
    onInput(e) {
      this.searchValue = e.detail.value;
      if (!this.searchValue.trim()) {
        this.showResult = false;
      }
    },
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空所有搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.historyList = [];
            try {
              uni.removeStorageSync('searchHistory');
              uni.showToast({
                title: '搜索历史已清空',
                icon: 'success'
              });
            } catch (error) {
              console.error('清空搜索历史失败:', error);
            }
          }
        }
      });
    },
    
    selectHistory(item) {
      this.searchValue = item;
      this.onSearch();
    },
    goToStationDetail(station) {
      // 将station数据编码后传递给详情页面
      const stationData = encodeURIComponent(JSON.stringify(station));
      uni.navigateTo({
        url: `/pages/station-detail/index?stationData=${stationData}`
      });
    },
    
    // 搜索充电站
    searchStations() {
      if (this.loading) return;
      
      this.loading = true;
      
      // 获取当前位置
      const currentLocation = this.getCurrentLocation();
      
      const params = {
        stationLat: currentLocation.latitude,
        stationLng: currentLocation.longitude,
        rows: '20',
        page: this.page.toString(),
        sortType: '1', // 默认按距离排序
        stationName: this.searchValue.trim() // 添加搜索名称参数
      };
      
      console.log('搜索充电站，参数:', params);
      
      getChargeStationList(params).then(res => {
        console.log('充电站搜索接口返回:', res);
        this.loading = false;
        
        if (res.code === 0 && res.success) {
          const records = res.data.records || [];
          
          if (this.page === 1) {
            // 第一页，直接替换数据
            this.stationList = records.map(item => ({
              id: item.stationId || 0,
              name: item.stationName || '未知站点',
              distance: (item.dist ? item.dist + 'km' : '距离未知'),
              facilities: item.facilities || '暂无设施信息',
              price: item.fee || '0.00',
              status: 'available',
              availableCount: item.fastRate ? parseInt(item.fastRate.split('/')[0]) : 0,
              totalCount: item.fastRate ? parseInt(item.fastRate.split('/')[1]) : 0,
              // 新增字段
              shopName: item.shopName || null,
              fastRate: item.fastRate || '0/0',
              parkFee: this.truncateText(item.parkFee || '停车信息未知', 20)
            }));
          } else {
            // 加载更多，追加数据
            const newRecords = records.map(item => ({
              id: item.stationId || 0,
              name: item.stationName || '未知站点',
              distance: (item.dist ? item.dist + 'km' : '距离未知'),
              facilities: item.facilities || '暂无设施信息',
              price: item.fee || '0.00',
              status: 'available',
              availableCount: item.fastRate ? parseInt(item.fastRate.split('/')[0]) : 0,
              totalCount: item.fastRate ? parseInt(item.fastRate.split('/')[1]) : 0,
              // 新增字段
              shopName: item.shopName || null,
              fastRate: item.fastRate || '0/0',
              parkFee: this.truncateText(item.parkFee || '停车信息未知', 20)
            }));
            this.stationList = [...this.stationList, ...newRecords];
          }
          
          this.total = res.data.total || 0;
          this.hasMore = this.stationList.length < this.total;
          this.page++;
          
          console.log('充电站搜索成功，数据:', this.stationList);
        } else {
          uni.showToast({
            title: res.msg || '搜索充电站失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('充电站搜索接口错误:', err);
        this.loading = false;
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      });
    },
    
    // 获取当前位置
    getCurrentLocation() {
      // 从缓存获取位置信息，如果没有则使用默认值
      const userLat = uni.getStorageSync('userLat');
      const userLng = uni.getStorageSync('userLng');
      
      return {
        latitude: userLat || '31.226215',
        longitude: userLng || '121.482595'
      };
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.searchStations();
      }
    },
    
    // 文本截断工具方法
    truncateText(text, maxLength) {
      if (!text || text.length <= maxLength) return text;
      return text.substring(0, maxLength) + '...';
    },

    // 清空输入框
    clearInput() {
      this.searchValue = '';
      this.showResult = false;
    },

    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync();
      this.statusBarHeight = systemInfo.statusBarHeight;
    },

    // 获取自定义右侧padding
    getCustomRightPadding() {
      try {
        const systemInfo = uni.getSystemInfoSync();
        const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
        
        // 计算需要的右外距：屏幕宽度 - 胶囊按钮左边界 + 额外间距
        const requiredPadding = systemInfo.screenWidth - menuButtonInfo.left; 
        this.customRightPadding = requiredPadding;
        
        console.log('计算的右外距:', this.customRightPadding, 'px');
        console.log('胶囊按钮信息:', menuButtonInfo);
      } catch (error) {
        console.error('计算右外距失败，使用默认值:', error);
        // 如果计算失败，使用默认值
        this.customRightPadding = 150; // 默认150px
      }
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style scoped>
.search-page {
  background: #fafbf8;
  min-height: 100vh;
  padding: 0;
}

.gradient-section {
  background: linear-gradient(180deg, #FFE9C7 50%, #fafbf8 100%);
  padding: 0 30rpx 0 30rpx;
}

.content-section {
  padding: 0 30rpx 0 30rpx;
}
.search-bar {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 24rpx;
  padding: 0 0 0 20rpx;
  height: 56rpx;
  margin: 20rpx 0 40rpx 0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}
.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 28rpx;
  background: transparent;
  margin: 0 10rpx;
}

.clear-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
  border-radius: 50%;
  background: #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.clear-btn:active {
  background: #e0e0e0;
}
.search-btn {
  background: #3f6cfe;
  color: #fff;
  border-radius: 24rpx;
  font-size: 28rpx;
  padding: 0rpx 32rpx;
  height: 48rpx;
  line-height: 48rpx;
  margin: 10rpx 10rpx 10rpx 10rpx;
  flex-shrink: 0;
}
.history-card {
  background: #fff;
  border-radius: 24rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.history-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}
.history-title {
  font-size: 28rpx;
  color: #222;
  font-weight: bold;
}
.history-clear {
  margin-left: 10rpx;
}
.history-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx 20rpx;
}
.history-tag {
  background: #f5f5f5;
  color: #666;
  font-size: 24rpx;
  border-radius: 24rpx;
  padding: 8rpx 28rpx;
  margin-bottom: 10rpx;
}
.history-empty {
  text-align: center;
  padding: 40rpx 0;
}
.empty-text {
  font-size: 28rpx;
  color: #999;
}

.station-jam {
  background: linear-gradient(180deg, #b97a56 0%, #eac9b0 100%);
  border-bottom-right-radius: 16rpx;
  padding: 0 24rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: -5rpx;
  left: -5rpx;
}
.station-jam-text {
  color: #fff;
  font-size: 22rpx;
  font-weight: bold;
}
.station-list {
  background: transparent;
  padding-bottom: 120rpx;
}
.station-item {
  width: 85%;
  margin: 0 auto 20rpx auto;
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 4rpx 16rpx rgba(255, 153, 0, 0.08);
  padding: 30rpx;
  display: flex;
  position: relative;
}

.station-item-with-shop {
  position: relative;
}

.station-item-with-shop::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 1rpx;
  height: 100%;
  background: linear-gradient(to bottom, rgba(234, 201, 188, 1), rgba(232, 207, 188, 0.3));
}

.station-item-with-shop::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 1rpx;
  background: linear-gradient(to right, rgba(185, 122, 86, 1), rgba(232, 207, 188, 0.3));
}

.station-info {
  flex: 1;
}

.station-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.station-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.station-distance {
  display: flex;
  align-items: center;
  border: 1rpx solid #e5e5e5;
  border-radius: 24rpx;
  padding: 4rpx 8rpx;
}

.distance-text {
  font-size: 24rpx;
  color: #666;
}

.station-details {
  margin-bottom: 15rpx;
}

.station-facilities {
  font-size: 24rpx;
  color: #666;
}

.station-pricing {
  display: flex;
  align-items: baseline;
}

.price-label {
  font-size: 24rpx;
  color: #ff6b35;
}

.price-amount {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b35;
}

.price-unit {
  font-size: 24rpx;
  color: #ff6b35;
  margin-right: 20rpx;
}

.station-rating {
  display: flex;
  align-items: center;
  background: none;
  padding: 0;
}

.station-rating-icon {
  width: 36rpx;
  height: 36rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #bfc3c9 0%, #e6e8eb 100%);
  margin-right: 0;
}

.station-rating-rateIcon {
  width: 36rpx;
  height: 36rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #ff6b35 0%, #ffb59a 100%);
  margin-right: 0;
}

.station-rating-p {
  color: #fff;
  font-weight: bold;
  font-size: 24rpx;
}

.station-rating-rate {
  color: #fff;
  font-size: 20rpx;
  font-weight: bold;
}

.station-rating-text-bg {
  background: #f5f6f7;
  border-radius: 0 8rpx 8rpx 0;
  padding: 0 12rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
}

.station-rating-text-numBg {
  background: #fff7f5;
  border-radius: 0 8rpx 8rpx 0;
  padding: 0 12rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
}

.station-rating-text {
  color: #888;
  font-size: 22rpx;
}

.station-rating-text-num {
  color: #ff6b35;
  font-size: 20rpx;
  font-weight: bold;
}

.station-status {
  display: flex;
  align-items: center;
  margin-left: auto;
}

.member-price-badge {
  display: inline-flex;
  align-items: center;
  height: 36rpx;
  border-radius: 8rpx;
  overflow: hidden;
  margin-bottom: 10rpx;
}

.member-price-label {
  background: #ff6b35;
  color: #fff;
  font-size: 18rpx;
  font-weight: bold;
  padding: 0 12rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
  border-radius: 8rpx 0 0 8rpx;
  box-sizing: border-box;
}

.member-price-value {
  position: relative;
  background: #fff;
  color: #ff6b35;
  font-size: 18rpx;
  font-weight: bold;
  padding: 0 16rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
  border-radius: 0 8rpx 8rpx 0;
  border: 2rpx solid #ff6b35;
  border-left: none;
  box-sizing: border-box;
}

.member-price-value::before {
  content: '';
  position: absolute;
  left: -12rpx;
  top: 0;
  width: 24rpx;
  height: 36rpx;
  background: #fff;
  border-radius: 18rpx 0 0 18rpx;
  z-index: 1;
}

/* 底部提示 */
.list-end {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

.end-line {
  flex: 1;
  height: 1rpx;
  background: #e0e0e0;
  background-image: linear-gradient(to right, transparent 50%, #e0e0e0 50%);
  background-size: 8rpx 1rpx;
}

.end-text {
  font-size: 24rpx;
  color: #999;
  margin: 0 20rpx;
}

/* 加载更多提示 */
.loading-more {
  text-align: center;
  padding: 30rpx 0;
}

.loading-text {
  font-size: 24rpx;
  color: #999;
}

/* 没有更多数据提示 */
.no-more {
  text-align: center;
  padding: 30rpx 0;
}

.no-more-text {
  font-size: 24rpx;
  color: #ccc;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 状态栏占位 */
.status-bar {
}

/* 顶部返回按钮区域 */
.header-section {
  background: transparent;
  border-radius: 30rpx;
  padding: 6rpx 0 6rpx 6rpx;
  display: flex;
  align-items: center;
  margin: 0 10rpx 10rpx 10rpx;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-title-section {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.back-button:active {
  opacity: 0.7;
}
</style> 